<template>
  <main-view @mapLoaded="mapLoaded" :url="sceneUrl" />
  <div class="back" v-if="showbtn" @click="back">
    <div class="back-text">返 回</div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed, watch } from "vue";
import MainView from "@/components/map/main-view/main-view.vue";
import { getQueryString } from "@/utils/map-util";
import * as mars3d from "mars3d";
const Cesium = mars3d.Cesium;
// import * as mapWork from "./map";
import { useMapStore } from "@/stores/counter";
const mapStore = useMapStore();

const sceneUrl = computed(() => getQueryString("url"));

const emit = defineEmits([
  "mapLoaded",
  "pointclick",
  "mapzoomchange",
  "projectclick",
]);

let thismap;
let xzqGraphicLayer;
let xzqdata;
let projectGraphicLayer;
let filename = "";

let _level = 0;

function mapLoaded(map: any) {
  thismap = map;
  mapStore.map = map;
  // mapStore.initmap();
  //初始化地图之后的操作
  xzqGraphicLayer = new mars3d.layer.GraphicLayer({
    name: "行政区点图层",
    id: 20, // 图层管理 中使用，父节点id
  });
  map.addLayer(xzqGraphicLayer);

  //接收区域范围内的点线面对象图层
  projectGraphicLayer = new mars3d.layer.GraphicLayer({
    name: "工程图层",
    id: 30, // 图层管理 中使用，父节点id
  });
  map.addLayer(projectGraphicLayer);

  projectGraphicLayer.on(mars3d.EventType.click, (e) => {
    // console.log(e.graphic.attr);
    emit("projectclick", e.graphic.attr);
  });

  //接收上传时的点线面对象图层
  let fileGraphicLayer = new mars3d.layer.GraphicLayer({
    name: "上传图层",
    id: 40, // 图层管理 中使用，父节点id
  });
  map.addLayer(fileGraphicLayer);

  xzqGraphicLayer.on(mars3d.EventType.click, (e) => {
    if (e.graphic.attr.clickable != false) {
      const attr = e.graphic.attr;
      if (attr.children && attr.children.length > 0) {
        const bbox = {
          xmin: e.graphic.attr.bbox[0],
          xmax: e.graphic.attr.bbox[2],
          ymin: e.graphic.attr.bbox[1],
          ymax: e.graphic.attr.bbox[3],
        };
        emit("pointclick", attr.type, attr.city, attr.name, bbox);
      } else {
        emit("pointclick", attr.type, attr.city, attr.name, null);
      }
    }
  });

  mars3d.Util.fetchJson({
    url: `${"/"}data/xzq.json?time=${new Date().getTime()}`,
  }).then((data: any) => {
    xzqdata = data;
    // showxzqByAttribute("辽宁省", "all", false);

    emit("mapLoaded", map);
  });

  map.on(mars3d.EventType.wheel, (e) => {
    if (e.sourceTarget.level < _level) {
      const layer = e.target.getLayerById(20);
      const attr = layer.graphics[0].attr;
      // console.log("layer", layer);
      // console.log("type", attr.type);

      if (e.sourceTarget.level < 10 && attr.type == "区") {
        emit("mapzoomchange", "省", attr.city);
      } else if (
        e.sourceTarget.level == 10 &&
        attr.type == "区" &&
        layer.graphics.length == 1
      ) {
        emit("mapzoomchange", "市", attr.city);
      }
    }

    // console.log("level", e.sourceTarget.level);
    // console.log("_level", _level);
    _level = e.sourceTarget.level;
  });
}

const showbtn = ref(false);

const back = () => {
  const layer = thismap.getLayerById(20);
  const attr = layer.graphics[0].attr;
  if (attr.type !== "市") {
    if (layer.graphics.length > 1) {
      emit("mapzoomchange", "省", attr.city);
      thismap.flyHome({
        duration: 0.5,
      });
    } else {
      emit("mapzoomchange", "市", attr.city);
      let _attr = xzqdata.filter((item) => item.name == attr.city)[0];
      const bbox = {
        xmin: _attr.bbox[0],
        xmax: _attr.bbox[2],
        ymin: _attr.bbox[1],
        ymax: _attr.bbox[3],
      };

      thismap.flyToExtent(bbox, {
        scale: 1.5,
        duration: 0.5,
      });
    }
  }
};
/**
 * 根据类型和列表显示特定的行政区图形
 * @param {string} type - 行政区类型，如"辽宁省"或其他下级行政区
 * @param {string} name - 行政区名称，如"辽宁省"或其他下级行政区
 * @param {string|array} list - 需要显示的行政区列表，"all"表示显示全部*
 * @param {object} isfly - 是否飞行定位，用于调整视角
 * @param {object} bbox - 行政区的边界框，用于调整视角
 */
const showxzqByAttribute = (type, name, list, isfly, bbox) => {
  xzqGraphicLayer.clear();
  let data;
  if (type == "省") {
    showbtn.value = false;
    data = xzqdata;
  } else {
    showbtn.value = true;
    _level = 0;
    data = xzqdata.filter((item) => item.name == name)[0].children;
  }

  data.map((item) => {
    if (list == "all" || list.indexOf(item.name) != -1) {
      const graphic = new mars3d.graphic.BillboardEntity({
        position: item.geom,
        style: {
          image: "/img/marker/marker_blue.png",
          scale: 0.8,
          scaleByDistance: new Cesium.NearFarScalar(1000, 0.5, 1000000, 0.3),
          clampToGround: true, // 贴地
          visibleDepth: false, // 是否被遮挡
          label: {
            text: item.name,
            font_size: 20,
            color: "#FFFFFFFF",
            outline: true,
            outlineWidth: 3,
            outlineColor: Cesium.Color.BLACK,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffsetY: -40,
            clampToGround: true, // 贴地
            visibleDepth: false, // 是否被遮挡
          },
          highlight: {
            scale: 1.1,
            image: "/img/marker/marker_origin.png",
            label: {
              color: "#F0A210FF",
            },
          },
        },
        attr: item,
      });
      xzqGraphicLayer.addGraphic(graphic);
    } else {
      const graphic = new mars3d.graphic.BillboardEntity({
        position: item.geom,
        style: {
          image: "/img/marker/marker_grey.png",
          scale: 0.8,
          scaleByDistance: new Cesium.NearFarScalar(1000, 0.5, 1000000, 0.3),
          clampToGround: true, // 贴地
          visibleDepth: false, // 是否被遮挡
          label: {
            text: item.name,
            font_size: 20,
            color: "#FFFFFFFF",
            outline: true,
            outlineWidth: 3,
            outlineColor: Cesium.Color.BLACK,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffsetY: -40,
            clampToGround: true, // 贴地
            visibleDepth: false, // 是否被遮挡
          },
        },
        attr: { clickable: false, ...item },
      });
      if (type != "区") xzqGraphicLayer.addGraphic(graphic);
    }
  });
  if (!isfly) return;
  if (type == "市") {
    thismap.flyToExtent(bbox, {
      scale: 1.5,
      duration: 0.5,
    });
  } else if (type == "区") {
    xzqGraphicLayer.flyTo({
      duration: 0.5,
      radius: 30000,
    });
  }
};
window.showxzqByAttribute = showxzqByAttribute;
const flytoExtend = (bbox) => {
  thismap.flyToExtent(bbox, {
    scale: 1.5,
    duration: 0.5,
  });
};

const addProject = (data) => {
  const geojson = JSON.parse(data);
  filename = geojson.fileName;
  if (geojson.features[0].geometry.type === ("Point" || "MultiPoint")) {
    projectGraphicLayer.loadGeoJSON(geojson, {
      type: "pointP",
      // clear: true,
      style: {
        color: "#ff0000",
        pixelSize: 10,
        clampToGround: true,
        outlineColor: "#ffffff",
        outlineWidth: 2,
      },
      onEachFeature: function (feature) {
        feature.attr = { ...feature.attr, filename: filename };
        return feature;
      },
    });
    // console.log(projectGraphicLayer);
  } else if (
    geojson.features[0].geometry.type === ("LineString" || "MultiLineString")
  ) {
    projectGraphicLayer.loadGeoJSON(geojson, {
      type: "polylineP",
      // clear: true,
      style: {
        width: 2,
        clampToGround: true,
        color: "#ff0000",
      },
      onEachFeature: function (feature) {
        feature.attr = { ...feature.attr, filename: filename };
        return feature;
      },
    });
    // console.log(projectGraphicLayer);
  } else if (
    geojson.features[0].geometry.type === ("Polygon" || "MultiPolygon")
  ) {
    projectGraphicLayer.loadGeoJSON(geojson, {
      type: "polygonP",
      // clear: true,
      // flyto: true,
      style: {
        color: "#ff4454",
        opacity: 0.3,
        outline: true,
        clampToGround: true,
        outlineWidth: 3,
        outlineColor: "#ffffff",
      },
      onEachFeature: function (feature) {
        feature.attr = { ...feature.attr, filename: filename };
        return feature;
      },
    });
    // console.log(projectGraphicLayer);
  }
};

const clearProject = () => {
  projectGraphicLayer.clear();
};
window.clearProject = clearProject;
window.addProject = addProject;

onUnmounted(() => {
  thismap = null;
});

defineExpose({
  showxzqByAttribute,
  flytoExtend,
  addProject,
  clearProject,
});
</script>

<style lang="less">
.back {
  position: absolute;
  right: 50px;
  top: 50%;
  z-index: 1000 !important;
  cursor: pointer;
  width: 5rem;
  height: 5rem;
  border-radius: 2.5rem;
  background: #d1d1d1;
  opacity: 0.5;

  .back-text {
    color: #6d6d6d;
    font-size: 1.2rem;
    font-weight: bold;
    line-height: 5rem;
    text-align: center;
    user-select: none;
  }

  &:hover {
    background: #ffffff;
    opacity: 0.8;
    .back-text {
      color: #202020;
      font-size: 1.2rem;
    }
  }
}
</style>
